package com.yangaobo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yangaobo.dto.DeptInsertDTO;
import com.yangaobo.dto.DeptPageDTO;
import com.yangaobo.dto.DeptUpdateDTO;
import com.yangaobo.entity.Dept;
import com.yangaobo.excel.DeptExcel;
import com.yangaobo.exception.ServerErrorException;
import com.yangaobo.mapper.DeptMapper;
import com.yangaobo.service.DeptService;
import com.yangaobo.vo.DeptVO;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨奥博
 */
@Service
@CacheConfig(cacheNames = "Dept")
public class DeptServiceImpl implements DeptService {
    @Resource
    private DeptMapper deptMapper;

    @CacheEvict(allEntries = true)
    @Override
    public int insert(DeptInsertDTO dto) {
        Dept dept = BeanUtil.copyProperties(dto, Dept.class);
        if(StrUtil.isBlank(dto.getInfo())) {
            dept.setInfo("暂无描述");
        }
        dept.setDeleted(0);
        dept.setVersion(0L);
        dept.setUpdated(LocalDateTime.now());
        dept.setCreated(LocalDateTime.now());
        int result = deptMapper.insert(dept);
        if(result <= 0) {
            throw new ServerErrorException("DB添加失败");
        }
        return result;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Dept select(Long id) {
        Dept result = deptMapper.select(id);
        if(ObjectUtil.isNull(result)) {
            throw new ServerErrorException("DB查询失败");
        }
        return result;
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<DeptVO> list() {
        return deptMapper.list(new DeptPageDTO())
                .stream()
                .map(dept -> BeanUtil.copyProperties(dept, DeptVO.class))
                .collect(Collectors.toList());
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public PageInfo<Dept> page(DeptPageDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo<>(deptMapper.list(dto));
    }

    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(DeptUpdateDTO dto) {
        Dept dept = deptMapper.select(dto.getId());
        if (ObjectUtil.isNull(dept)) {
            throw new ServerErrorException("DB查询失败");
        }
        BeanUtil.copyProperties(dto, dept,
                CopyOptions.create().setIgnoreNullValue(true));
        dept.setUpdated(LocalDateTime.now());
        int result = deptMapper.update(dept);
        if(result <= 0) {
            throw new ServerErrorException("DB更新失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int delete(Long id) {
        int result = deptMapper.delete(id);
        if(result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteBatch(List<Long> ids) {
        int result = deptMapper.deleteBatch(ids);
        if(result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }

    @Override
    public List<DeptExcel> getExcelData() {
        return deptMapper.list(new DeptPageDTO())
                .stream()
                .map(dept -> {
                    DeptExcel deptExcel = BeanUtil.copyProperties(dept, DeptExcel.class);
                    if(ObjectUtil.isNotNull(dept.getRoom())) {
                        deptExcel.setRoomTitle(dept.getRoom().getTitle());
                    } else {
                        throw new ServerErrorException("部门关联房间不存在");
                    }
                    return deptExcel;
                })
                .collect(Collectors.toList());
    }

}
